<?php
namespace x\my;
use x\my\Curl;
class Umeng
{
    public static $appKey;
    public static $appSecret;
    public static $umengSecret;
    public static $type='ios';


    //获取签名
    static function getSign($data){
        $url = "http://msg.umeng.com/api/send";
        $str = "POST".$url.json_encode($data).self::$appSecret;
        return md5($str);
    }

    //获取签名
    static function createHeaders($type='urlencoded'){
        $nonce = rand();
        $time = time();
        $httpHeaders = [
            'App-Key:'.self::$appKey,
            'Nonce:'.$nonce,
            'Timestamp:'.$time,
            'Signature:'.sha1(self::$appSecret.$nonce.$time),
        ];
        switch ($type) {
            case 'json':
                $httpHeaders[] = "Content-Type:Application/json";
                break;
            case 'urlencoded':
            default:
                $httpHeaders[] = "Content-Type:application/x-www-form-urlencoded";
                break;
        }
        return $httpHeaders;
    }

    //发送融云消息
    public static function send($token, $content, $params=''){
        if(strlen($token)==64){
            self::$appKey = c('api.umeng.ios.appKey');
            self::$appSecret = c('api.umeng.ios.appSecret');
            self::$umengSecret = c('api.umeng.ios.umengSecret');
            $params = [
                'appkey'=>self::$appKey,
                'timestamp'=>$time,
                'device_tokens'=>$token,
                'type'=>'unicast',
                'payload'=>[
                    'aps' => [
                        'alert'=>[
                            'title'=>'',
                            'subtitle'=>'',
                            'body'=>$content,
                        ],
                        "badge"=>1,
                        "sound"=>'default',
                    ],
                ],
                'production_mode'=>false,  #true为正式环境
            ];
        }else if(strlen($token)==44){
            self::$appKey = c('api.umeng.android.appKey');
            self::$appSecret = c('api.umeng.android.appSecret');
            self::$umengSecret = c('api.umeng.android.umengSecret');
            $params = [
                'appkey'=>self::$appKey,
                'timestamp'=>$time,
                'device_tokens'=>$token,
                'type'=>'unicast',
                'payload'=>[
                    'body'=>[
                        'ticker'=>'七色淘品通知',
                        'title'=>'七色淘品',
                        'text'=>$content,
                        'after_open'=>'go_app'
                     ],
                     'display_type'=>'notification'
                 ],
                 'production_mode'=>true,  #true为正式环境
            ];
        }
        $time = time();
        $method = "POST";
        $url = "http://msg.umeng.com/api/send?sign=".self::getSign($params);
        $fields = json_encode($params);
        $rs = curl::execute($method, $url, $fields);
        $rs = json_decode($rs,true);
        return isset($rs['ret']) && $rs['ret']=='SUCCESS' ? true : false;
    }

    /**
    * 获取 Token 方法
    * @param  userId:用户 Id，最大长度 64 字节.是用户在 App 中的唯一标识码，必须保证在同一个 App 内不重复，重复的用户 Id 将被当作是同一用户。（必传）
    * @param  name:用户名称，最大长度 128 字节.用来在 Push 推送时显示用户的名称.用户名称，最大长度 128 字节.用来在 Push 推送时显示用户的名称。（必传）
    * @param  portraitUri:用户头像 URI，最大长度 1024 字节.用来在 Push 推送时显示用户的头像。（必传）
    * @return $json
    **/
    public static function getToken($userId, $name, $avatar='') {
        $method = "POST";
        $url = "http://api.cn.ronghub.com/user/getToken.json";
        $fields = [
            'userId' => $userId,
            'name'   => $name,
            'portraitUri' => $avatar
        ];
        $rs = curl::execute($method, $url, $fields, '', self::createHeaders('urlencoded'));
        $rs = json_decode($rs,true);
        return isset($rs['code']) && $rs['code']==200 ? $rs['token'] : false;
    }
}
